package com.example.rabbitmq.returnlistener;

import com.rabbitmq.client.*;

import java.io.IOException;

/**
 * @author： ygl
 * @date： 2019/06/15
 * @Description：
 */
public class MyProducer {

    public static void main(String[] args) throws Exception {

        // 1.创建ConnectionFactory
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("127.0.0.1");
        connectionFactory.setPort(5672);
        connectionFactory.setVirtualHost("/");
        // 2.通过链接工厂创建链接
        Connection connection = connectionFactory.newConnection();
        // 3.通过connection创建channel信道
        Channel channel = connection.createChannel();
        // 4.指定消息投递模式：消息的确认模式
        channel.confirmSelect();
        // 5.通过channel发送数据
        String exchangeName = "test_return_exchange";
        String routingKey = "abc.save";
        String msg = "hello rabbitmq send return message!";

        // 6.添加一个路由不可达监听
        channel.addReturnListener(new ReturnListener() {
            @Override
            public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("-------------hanlde return--------------");
                System.out.println("replyCode:"+replyCode);
                System.out.println("replyText:"+replyText);
                System.out.println("exchange:"+exchange);
                System.out.println("routingKey:"+routingKey);
                System.out.println("properties:"+properties);
                System.out.println("body:"+body.toString());
            }
        });

        // mandatory: true 消息不可路由不会删除消息
        channel.basicPublish(exchangeName, routingKey, true,null, msg.getBytes());

        // 6.关闭链接
//        channel.close();
//        connection.close();
    }
}
